package com.example.demo.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.lang.Console;
import com.example.demo.Constants;
import com.example.demo.model.CaptchaProperties;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;

@RequestMapping("/captcha")
@RestController
public class CaptchaController {
    private final long CAPTCHA_VALID_TIME = 60 * 1000;
    @Autowired
    private CaptchaProperties captchaProperties;
    @RequestMapping("get")
    public void get(HttpServletRequest request, HttpServletResponse response, HttpSession session){
        //定义图形验证码的长和宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(captchaProperties.getWidth(), captchaProperties.getHeight());
        //图形验证码写出，可以写出到文件，也可以写出到流
        try {
            lineCaptcha.write(response.getOutputStream());
            session.setAttribute(captchaProperties.getSession().getKey(), lineCaptcha.getCode());
            session.setAttribute(captchaProperties.getSession().getDate(), new Date());
            response.getOutputStream().close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    @RequestMapping("/check")
    public boolean check(String userInput, HttpSession session){
        if(!StringUtils.hasLength(userInput)){
            return false;
        }
        // 从 session 中获取信息
        String savedCode = (String) session.getAttribute(captchaProperties.getSession().getKey());
        Date savedTime = (Date) session.getAttribute(captchaProperties.getSession().getDate());
        if(!userInput.equalsIgnoreCase(savedCode)){
            return false;
        }
        if(System.currentTimeMillis() - savedTime.getTime() > CAPTCHA_VALID_TIME){
            return false;
        }
        return true;
    }
}
